/* eslint-disable */
import _ from 'lodash'
import http from './httpRequest'
import moment from 'dayjs'

export const getToken = () => {
    return sessionStorage.getItem('all_token')
}

export const setToken = (token: string) => {
    sessionStorage.setItem('all_token', token)
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key: string) {
    if (!key) {
        return true
    }
    return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1
}


/**
 * 树形结构
 * @param list 
 * @param id 
 * @param pId 
 * @returns 
 */
export function treeData(list: any[], id: string, pId: string) {
    let treeList: any[] = []
    if (id && pId) {
        list.forEach((res: any) => {
            const parent = list.find(next => next[id] === res[pId]);
            if (!parent) {
                treeList.push(res);
            } else {
                parent.children = parent.children || [];
                parent.children.push(res);
            }
        });
    }

    return treeList
}


/**
 * 附件下载
 * @param {*} payload 
 * @param {*} callback 
 * @param {*} method 
 */
export function download(payload: { url/*接口地址*/: string, filename/*文件名称*/: string, params/*接口参数*/: { [prop: string]: string | number | string[] | number[] }, _type/*文档类型*/: string }, callback/*回调函数，下载完毕执行*/: () => void, method = 'get', config/*axios配置*/ = <{ [prop: string]: string | number | string[] | number[] }>{}) {
    http({
        url: http.adornUrl(payload.url),
        method: method,
        [method.toLocaleUpperCase() === 'GET' ? 'params' : 'data']: (http as any)["adorn" + (method.toLocaleUpperCase() === 'GET' ? 'Params' : 'Data')]({
            ...payload.params
        }, false),
        responseType: 'blob',
        ...config
    }).then((res) => {
        const { data } = res
        let fileName = ''
        if (!payload.filename) {
            fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
        }
        const a = document.createElement('a')
        const blob = new Blob([data], { type: payload._type || 'text/plain' })
        const now = moment().format("YYYY-MM-DD HH:mm:ss");
        const nvg = window.navigator as any
        if (nvg.msSaveOrOpenBlob) {
            nvg.msSaveOrOpenBlob(
                blob,
                `file${now}_${payload.filename || fileName}`
            );
        } else {
            a.download = payload.filename || fileName
            a.href = URL.createObjectURL(blob)
            a.click()
        }
        callback && callback()
    }).catch(() => callback && callback())
}

export function parseZhNum(index: number) {
    const zhNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']

    return zhNums[index]
}

export function getParams(qForm: any) {
    const form: any = {}
    Object.keys(qForm).forEach(key => {
        const type = typeof qForm[key]
        if (['string', 'number'].includes(type)) {
            form[key] = qForm[key]
        }
    })
    return form
}

function toHump(name) {
    return name.replace(/\/(\w)/g, function (_all, letter) {
        return letter.toUpperCase();
    });
}


export async function dict(val: string | number, type: string) {
    const { data } = await http({
        url: http.adornUrl(`/base/mgt/dictData/dictDataSelector/${type}`),
        params: http.adornParams({
        })
    })
    if (val === 'list_all') {//返回字典数据集合
        return data.data
    }
    const items = data.data
    const item = items.find(res => res.dictValue === val)
    // console.log('dict-item', item, 'val', val);

    if (item) {
        return item.dictLabel
    }
    return ''
}

export function setFullPath(data) {
    data.forEach(res => {
        if (!res.fullPath) {
            res.fullPath = res.path
            if (!res.fullPath.startsWith('/')) {
                res.fullPath = '/' + res.fullPath
            }
        }
        if (res.meta) {
            res.title = res.meta.title
            res.icon = res.meta.icon
            if (res.icon === '#') {
                res.icon = ''
            }
        }
        if (res.children) {
            res.type = 'folder'
            res.children.forEach(next => {
                if (!next.path.startsWith('/')) {
                    next.path = '/' + next.path
                }
                next.fullPath = res.fullPath + next.path
                next.fullName = toHump(next.fullPath)
                next.parent = res
                if (next.children) {
                    next.type = 'folder'
                    setFullPath(res.children)
                } else {
                    next.type = 'file'
                    next.component = next.component || (res.fullPath + next.path)
                    if (next.meta) {
                        next.title = next.meta.title
                        next.icon = next.meta.icon
                        if (next.icon === '#') {
                            next.icon = ''
                        }
                    }
                }
            })
        } else {
            res.type = 'file'
            res.component = res.component || (res.fullPath)
            res.fullName = toHump(res.fullPath)
        }
    })
    return data
}

/**
 * 字段驼峰 替换成下划线_ label
 */
export function toUnderScore(label: string) {
    return label.replace(/([A-Z])/g, function (letter) {
        return '_' + letter.toLowerCase();
    });
}


export function joinNumber(n: number, p: string) {
    const str = n?.toString() || ''
    return str.replace(/\B(?=(\d{3})+(?!\d))/g, p)
}

export function setSize() {
    if (document.body.clientWidth > 1910) {
        if (document.body.clientHeight < 1070) {
            document.documentElement.style.fontSize = '86px'
        } else {
            document.documentElement.style.fontSize = '100px'
        }
    }
}

export function randomColor() {
    let str = "#";
    let arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
    for (let i = 0; i < 6; i++) {
        let num = parseInt((Math.random() * 16).toString());
        str += arr[num];
    }
    return str;
}